package com.godot.service;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import com.godot.entity.manager.GodotManger;

public class LoginService extends Service {
	
	//
	private static final int kActionLogin = 1;
	
	//
	private static final int kActionRegister = 2;

	@Override
	protected void doExcute() {
		super.doExcute();
	}
	
	@Override
	protected void dispatch() {
		super.dispatch();
		switch (_action) {
		case kActionLogin:
			this.Login();
			break;
		case kActionRegister:
			this.register();
			break;
		default:
			break;
		}
	}

	//注册
	private void register() {
		String name = _req.getParameter(kAttrName);
		String pwd = _req.getParameter(kAttrPassword);
		String email = _req.getParameter(kAttrEmail);
		GodotManger gm = new GodotManger(_pm);
		String key = gm.register(name, pwd, email);
		setSession(name, key, true);
		toForward(true);
	}

	//登录
	private void Login() {
		String name = _req.getParameter(kAttrName);
		String pwd = _req.getParameter(kAttrPassword);
		GodotManger gm = new GodotManger(_pm);
		String key = gm.login(name, pwd);
		setSession(name, key, key != null);
		toForward(true);
	}
	
	private void setSession(String name, String key, boolean flag) {
		_session.setAttribute(kSesLoginFlag, flag);
		if (flag) {
			_session.setAttribute(kAttrName, name);
			_session.setAttribute(kAttrKey, key);
		}
	}
	
	private void toForward(boolean flag) {
		RequestDispatcher rd = flag ? _req.getRequestDispatcher("/godot/main.jsp") : _req.getRequestDispatcher("");
		try {
			rd.forward(_req, _resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
